LINQ to XML - Language Integration Samples


LINQ, LINQ to XML, .NET Framework 4.0
LINQ, LINQ to XML, XML, Console Window, XML Documentation
Desktop, Data
en-US
6/28/2011

Introduction

These samples show how to integrate C# code with LINQ queries.

Building the Sample

  1. Open Program.cs
  2. Uncomment the line for the sample that you want to run; comment ones you don't want to run
  3. Press Ctrl + F5

Screenshot


Sample Code

C#
Edit|Remove
            [Category("Language Integration")] 
            [Description("Find all orders for customers in a List")] 
            public void XLinq79() 
            { 
                XDocument doc = XDocument.Load("nw_orders.xml"); 
                List<Customer> customers = SomeMethodToGetCustomers(); 
                var result = 
                    from customer in customers 
                    from order in doc.Descendants("Orders") 
                    where 
                        customer.id == (string)order.Element("CustomerID") 
                    select 
                        new { custid = (string)customer.id, orderdate = (string)order.Element("OrderDate") }; 
                foreach (var tuple in result) 
                    Console.WriteLine("Customer id = {0}, Order Date = {1}", 
                                        tuple.custid, tuple.orderdate); 
 
            } 
            class Customer 
            { 
                public Customer(string id) { this.id = id; } 
                public string id; 
            } 
            static List<Customer> SomeMethodToGetCustomers() 
            { 
                List<Customer> customers = new List<Customer>(); 
                customers.Add(new Customer("VINET")); 
                customers.Add(new Customer("TOMSP")); 
                return customers; 
            }

Source Code Files

More Information

For more information on LINQ to XML: http://msdn.microsoft.com/en-us/library/bb387098.aspx